package com.sunyard.redission.demos.web;


import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;

/**
 * @author liugang
 * @Type com.sunyard.sunam.utils
 * @Desc
 * @date 14:23 2021/11/16
 */
@Slf4j
public class FileUtils {


    /**
     * 下载
     *
     * @param response 响应
     * @param filename 文件名
     * @param input  附件内容
     * @throws IOException 异常
     */
    public static void writeAttachment(HttpServletResponse response, String filename, InputStream input){
        if (response == null || filename == null || input == null) {
            throw new IllegalArgumentException("response,filename,input不能为null");
        }
        try (ServletOutputStream output = response.getOutputStream()) {
            // 设置响应头
            String encodedFilename = URLEncoder.encode(filename, StandardCharsets.UTF_8.toString())
                    .replace("+", "%20");
            response.setHeader("Content-Disposition", "attachment; filename=" + encodedFilename);

            // 明确设置字符集和内容类型
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            response.setCharacterEncoding(StandardCharsets.UTF_8.name());

            // 使用更大的缓冲区提高性能（8KB）
            byte[] buffer = new byte[8192];
            int bytesRead;

            while ((bytesRead = input.read(buffer)) != -1) {
                output.write(buffer, 0, bytesRead);
            }
            log.info("导出完毕");
            output.flush();
        } catch (IOException e) {
            throw new RuntimeException("下载文件失败 " + filename, e);
        } finally {
            try {
                input.close();
            } catch (IOException e) {
                log.info("输入流关闭异常:{}", e.getMessage());
            }
        }
    }

}
